package cn.kgc.javaweb.dao;

import cn.kgc.javaweb.entity.Student;
import cn.kgc.javaweb.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/3/25
 */
public class StudentDaoImpl implements StudentDao {

    // 分页查询页面需要显示的数据
    @Override
    public List<Student> findByPage(int page, int limit) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select  *  from student limit ?,?";
        int start = (page-1)*limit;
        try {
            List<Student> students = queryRunner.query(sql, new BeanListHandler<>(Student.class), start, limit);
            return students;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    //查询所有的记录数
    @Override
    public long selectTotal() {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select count(*) from student";
        try {
            long count = (long)queryRunner.query(sql, new ScalarHandler<>());
            return  count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int insertStudent(Student student) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "insert into student(stuName,age,sex,address,tel)values(?,?,?,?,?)";

        try {
            int line = queryRunner.update(sql, student.getStuName(), student.getAge(), student.getSex(), student.getAddress(), student.getTel());
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return 0;
    }

    @Override
    public int update(Student student) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "update student set stuName =? ,age = ? ,sex= ?,address = ?, tel = ? where id = ?";

        try {
            int line = queryRunner.update(sql, student.getStuName(), student.getAge(), student.getSex(), student.getAddress(), student.getTel(), student.getId());
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return 0;
    }

    @Override
    public int del(int id) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "delete from student where id = ?";

        try {
            int line = queryRunner.update(sql, id);
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
